package com.rybbaby.tss.platform.websocket.service;

import java.io.IOException;
import java.sql.Timestamp;
import com.rybbaby.tss.core.utils.JSONUtil;
import com.rybbaby.tss.platform.websocket.handler.MsgWebSocketHandler;
import com.rybbaby.tss.platform.websocket.pojo.BroadcastMessageInfo;
import com.rybbaby.tss.platform.websocket.pojo.WebSocketMessageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;

/**
 * @author 谢进伟
 * @description 系统websocket消息服务
 * @createDate 2017-02-15 下午8:36:40
 */
@Component
public class PlatformWebsocketMsgService {

    @Autowired
    MsgWebSocketHandler handler;

    /**
     * @param fromUserId   发送者Id
     * @param fromUserName 发送者姓名
     * @param toUserId     接受者姓名
     * @param content      消息内容
     * @throws IOException
     */
    public void sendMessageToUser(String fromUserId, String fromUserName, String toUserId, String content) throws IOException {
        WebSocketMessageInfo wsmg = new WebSocketMessageInfo();
        wsmg.setFrom(fromUserId);
        wsmg.setFromName(fromUserName);
        wsmg.setTo(toUserId);
        wsmg.setContent(content);
        wsmg.setSendTime(new Timestamp(System.currentTimeMillis()));
        handler.sendMessageToUser(toUserId, new TextMessage(JSONUtil.toJsonStr(wsmg)));
    }

    /**
     * 发布系统广播（群发）
     *
     * @param title   标题
     * @param content 内容
     * @throws IOException
     */
    public BroadcastMessageInfo broadcast(String title, String content) throws IOException {
        BroadcastMessageInfo msg = new BroadcastMessageInfo();
        msg.setSendTime(new Timestamp(System.currentTimeMillis()));
        msg.setTitle(title);
        msg.setContent(content);
        handler.broadcast(new TextMessage(JSONUtil.toJsonStr(msg)));
        return msg;
    }

}